<template>
  <div class="wrap call-summary">
      <el-aside class="card" style="width: 160px">
        <el-card :body-style="{padding: '0 10px'}">
          <div class="card-item">
            <p class="num">{{phoneAccountCalls.inCalls || 0}}</p>
            <p class="num-word">{{$t('monitor.todayInSum')}}</p>
          </div>
          <div class="card-item">
            <p class="num">{{inCallAgentCount || 0}}</p>
            <p class="num-word">{{$t('workbench.ringSum')}}</p>
          </div>
          <div class="card-item">
            <p class="num">{{phoneAccountCalls.inComplete || 0}}</p>
            <p class="num-word">{{$t('monitor.comingSum')}}</p>
          </div>
          <div class="card-item">
            <p class="num">{{phoneAccountCalls.inCalls - phoneAccountCalls.inComplete || 0}}</p>
            <p class="num-word">{{$t('monitor.uncomingSum')}}</p>
          </div>
          <div class="card-item">
            <p class="num">{{phoneAccountCalls.inComplete | rate(phoneAccountCalls.inCalls)}}</p>
            <p class="num-word">{{$t('workbench.completingRate')}}</p>
            <el-popover
              placement="right"
              trigger="hover"
              :content="$t('monitor.tooltipCallRate')"
              popper-class="common-tootip"
            >
              <span slot="reference" class="tooltip fr"><i class="iconfont icon-wenzishuoming"></i></span>
            </el-popover>
          </div>
          <div class="card-item">
            <p class="num">{{phoneAccountCalls.inComplete | rate(inCallAgentCount)}}</p>
            <p class="num-word">{{$t('workbench.completingAgentRate')}}</p>
            <el-popover
              placement="right"
              trigger="hover"
              :content="$t('monitor.tooltipAgentRate')"
              popper-class="common-tootip"
            >
              <span slot="reference" class="tooltip fr"><i class="iconfont icon-wenzishuoming"></i></span>
            </el-popover>
          </div>
          <div class="card-item">
            <p class="num">{{summary.waitCountTotal || 0}}</p>
            <p class="num-word">{{$t('monitor.waitCountTotal')}}</p>
          </div>
          <div class="card-item">
            <p class="num">{{phoneAccountCalls.inType ? phoneAccountCalls.inType.InQueueLeak : 0}}</p>
            <p class="num-word">{{$t('monitor.queuingLeak')}}</p>
          </div>
          <div class="card-item">
            <p class="num">{{phoneAccountCalls.inType ? phoneAccountCalls.inType.InLimit : 0}}</p>
            <p class="num-word">{{$t('monitor.inlimit')}}</p>
          </div>
          <div class="card-item">
            <p class="num">{{phoneAccountCalls.outCalls || 0}}</p>
            <p class="num-word">{{$t('monitor.outCallSumToday')}}</p>
          </div>
          <div class="card-item">
            <p class="num">{{phoneAccountCalls.outComplete || 0}}</p>
            <p class="num-word">{{$t('monitor.outSum')}}</p>
          </div>
          <div class="card-item">
            <p class="num">{{phoneAccountCalls.outComplete | rate(phoneAccountCalls.outCalls)}}</p>
            <p class="num-word">{{$t('monitor.outSumRate')}}</p>
          </div>
        </el-card>
      </el-aside>
    <div class="main1">
      <div class="tips" v-if="$store.state.session.user.type === 'agent'">{{$t('monitor.tips2')}}</div>
      <div class="agent" style="margin-bottom: 25px">
        <div v-for="(item, index) in licenceType" :key="index" class="agent-cont">
          <span class="agent-title">{{item.label}}</span>
          <span class="padding-r">
            <span class="agent-sub" v-once>{{$t('monitor.loginedAgent')}}</span>
            <span class="blod">{{item.online}}</span>
          </span>
          <span class="padding-r">
            <span class="agent-sub" v-once>{{$t('monitor.offlineAgent') + $t('public.colon')}}</span>
            <span class="blod">{{item.offline}}</span>
          </span>
          <span>
            <span class="agent-sub">{{$t('monitor.liceceAgent')}}</span>
            <span class="blod">{{item.value1}}</span>
          </span>
        </div>
        <div style="clear: both"></div>
      </div>
      <div>
        <affix :label="$t('monitor.callMonitor')" :bodyStyle="{paddingTop:'6px'}" v-once></affix>
        <el-container >
          <el-main class="main">
            <div class="header clearBoth">
              <time class="header-time">{{$t('monitor.currTime')}}：{{commonData.time}}</time>
              <div class="fr">
                <span>{{$t('monitor.showTable')}}</span>
                <el-select v-model="showTable" multiple collapse-tags :placeholder="$t('public.all')" size="mini" class="mulit-select">
                <el-option
                  v-for="(item, index) in showOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.value">
                </el-option>
              </el-select>
              </div>
            </div>
            <el-row :gutter="60">
              <el-col :span="12" class="border-line" v-if="!showTable.length || showTable.indexOf('1') !== -1">
                <div class="title">{{$t('monitor.callAgentMonitor')}}
                  <el-popover
                    placement="bottom"
                    width="500"
                    trigger="hover"
                    popper-class="common-tootip"
                  >
                    <div v-html="$t('monitor.tooltipCallAgent')"></div>
                    <span slot="reference"><i class="iconfont icon-wenzishuoming"></i></span>
                  </el-popover>
                  <i class="iconfont icon-peizhi" @click="monitorWarn('user')"></i>
                </div>

                <el-row :gutter="10">
                  <div class="pie"><span class="pie-out">{{$t('monitor.logout2')}}{{pieData.out}}</span><span>{{$t('monitor.login2')}}{{pieData.on}}</span></div>
                  <monitor-pie :data="pieData.pie" style="height: 260px;"></monitor-pie>
                </el-row>
              </el-col>
              <el-col :span="12" class="monitor-table" v-if="!showTable.length || showTable.indexOf('2')!== -1">
                <div class="title">{{$t('monitor.top5')}}</div>
                <table class="el-table el-table--striped el-table--enable-row-hover" border="0" cellspacing="0">
                  <thead>
                  <tr>
                    <th><div class="cell" v-once>{{$t('monitor.top5Rank')}}</div></th>
                    <th><div class="cell" v-once>{{$t('public.agent')}}</div></th>
                    <th><div class="cell" v-once>{{$t('monitor.top5In')}}</div></th>
                    <th><div class="cell" v-once>{{$t('monitor.top5Out')}}</div></th>
                  </tr>
                  </thead>
                  <tbody class="el-table__body">
                  <tr v-for="(item, index) in top5" :key="index">
                    <td><i class="iconfont top-red" :class="index ? ('icon-NO' + index):'icon-NO'"></i>&nbsp;{{index >2? (index+1) : ''}}</td>
                    <td>{{phonePeers[item].agentNo}}</td>
                    <td>{{phonePeers[item].answerCount}}</td>
                    <td>{{phonePeers[item].outCalls}}</td>
                  </tr>
                  </tbody>
                </table>
              </el-col>
            </el-row>
            <div class="block" v-if="!showTable.length || showTable.indexOf('3')!== -1">
              <div class="title">{{$t('monitor.callIn6Hours')}}<i class="iconfont icon-peizhi" @click="monitorWarn('incall')"></i></div>
              <monitor-line :data="callInData" ref="monitorLine1"></monitor-line>
            </div>
            <div class="block" v-if="(!showTable.length || showTable.indexOf('4')!== -1) && this.$store.state.session.account.isSouthEastAsia !== 'true'">
              <div class="title">{{$t('monitor.callInArea')}}<i class="iconfont icon-peizhi" @click="monitorWarn('area')"></i></div>
              <area-map ref="monitorArea"></area-map>
            </div>
            <div class="block" v-if="!showTable.length || showTable.indexOf('5')!== -1">
              <div class="title">{{$t('monitor.callHeartChart')}}<i class="iconfont icon-peizhi" @click="monitorWarn('limit')"></i></div>
              <monitorHeart ref="monitorHeart"></monitorHeart>
            </div>
          </el-main>
        </el-container>
        <warn-setting
          :type="dialogObj.type"
          :selectState="dialogObj.selectState"
          :data="dialogObj.data"
          :title="dialogObj.title"
          ref="warn"
          @save="save"
        ></warn-setting>
      </div>
    </div>
  </div>
</template>
<script>
  import { m7Language } from '@/utils/m7Utils.js'
  import Affix from '../../ui-modules/affix/Affix'
  import areaMap from './base/area'
  import monitorHeart from './base/monitorHeart'
  import monitorPie from './base/monitorPie'
  import monitorLine from './base/monitorLine'
  import warnSetting from './base/warnSetting'
  import {monitorCallConfig} from '@/utils/monitor'
  let statusCustColorArr = {
    0: '#ED5870',
    1: '#F48C4D',
    2: '#FBB100',
    3: '#66BDC7',
    4: '#BBC9D6',
    5: '#CECECE'
  }
  export default {
    name: 'callSummary',
    data () {
      return {
        showTable: [],
        showOptions: [
          {name: this.$t('monitor.callAgentMonitor'), value: '1'},
          {name: this.$t('monitor.top5'), value: '2'},
          {name: this.$t('monitor.callIn6Hours'), value: '3'},
          {name: this.$t('monitor.callInArea'), value: '4'},
          {name: this.$t('monitor.callHeartChart'), value: '5'}
        ],
        select: monitorCallConfig(),
        dialogObj: {
          type: '',
          selectState: [],
          data: [],
          title: ''
        },
        callInData: {
          xCategories: [],
          seriesArray: []
        }
      }
    },
    props: {
    },
    inject: ['commonData', 'summary', 'init', 'phonePeers', 'licenceType', 'agentType'],
    components: {
      Affix,
      areaMap,
      monitorHeart,
      monitorPie,
      warnSetting,
      monitorLine
    },
    computed: {
      top5 () {
        let _array = Object.keys(this.phonePeers)
        _array.sort(this.sortArray)
        return _array.sort(this.sortArray).slice(0, 5)
      },
      // 流转到坐席的呼入数
      inCallAgentCount () {
        let accountCalls = this.phoneAccountCalls
        let inType = accountCalls.inType || {}
        return accountCalls.inComplete + inType.InNotDeal
      },
      // 饼图渲染
      pieData () {
        let state = this.summary.agents
        let arr = []
        let on = 0
        let out = 0
        let n = 0
        for (let i in state) {
          let item = state[i]
          if (item.value > 0) {
            if (i === 'ready' || i === 'offline') {
              out += state[i].value
            } else {
              on += state[i].value
            }
            let m7Name = m7Language('globalChineseKey.' + state[i].name, null, true) || state[i].name
            let data = {name: m7Name, y: state[i].value, color: ''}
            if (i === 'ready') {
              data.color = '#9761ad'
            } else if (i === 'offline') {
              data.color = '#5F89BB'
            } else if (i === '0') {
              data.color = '#79B05D'
            } else {
              data.color = statusCustColorArr[n % 6]
              n++
            }
            arr.push(data)
          }
        }
        return {pie: arr, on, out}
      },
      phoneAccountCalls () {
        let pbx = this.$store.state.session.user.pbx
        let data = this.$store.state.cti.globalLet.phone_accountCalls
        return data[pbx] || {}
      },
      updateheartChart () {
        let pbx = this.$store.state.session.user.pbx
        let data = this.$store.state.monitor.table.phone_heartBeat
        return data[pbx]
      }
    },
    filters: {
      rate (value, all) {
        if (all) {
          return Math.round(value * 100 / all) + '%'
        }
        return '0%'
      }
    },
    watch: {
      updateheartChart: {
        deep: true,
        handler (newV) {
          let data = newV
          if (data) {
            this.callInData.seriesArray.forEach((one) => {
              let item = data[one.valueName].split(':') || []
              if (item.length < 2) {
                return
              }
              let time = parseInt(item[0])
              let num = parseInt(item[1])
              one.data.push({x: time, y: num})
              if (one.data.length > 360) {
                one.data.shift()
              }
            })
          }
        }
      }
    },
    methods: {
      sortArray (a, b) {
        return (this.phonePeers[b].answerCount + this.phonePeers[b].outCalls) - (this.phonePeers[a].answerCount + this.phonePeers[a].outCalls)
      },
      monitorWarn (type) {
        this.dialogObj.type = type
        this.dialogObj.title = this.select[type + 'Name']
        this.dialogObj.selectState = this.select[type]
        this.$store.dispatch('queryMonitorWarningCfg', {module: 'call', pbx: this.$store.state.session.user.pbx}).then((res) => {
          if (res.data && res.data.length) {
            this.dialogObj.data = res.data[0].config[type] || []
          }
          this.$refs.warn.open()
        })
      },
      save (data) {
        data.module = 'call'
        data.pbx = this.$store.state.session.user.pbx
        this.$store.dispatch('updateMonitorWarningCfg', data).then((res) => {
          this.$refs.warn.handleClose()
        })
      },
      getCallInDataIn6Hours (type) {
        // IncomingData 呼入总数
        // IncomingCompleteData 呼入接听书
        // MisscomingData未接通总数
        // LimitcomingData  并发限制
        // queueData 排队数
        this.$store.dispatch('initHeartBeat').then((res) => {
          let datas = res || {}
          if (type === 'init') {
            let seriesArray = []
            let headerConfig = {limitcomingData: this.$t('call.limit'), queue: this.$t('monitor.queueNumber'), incomingComplete: this.$t('monitor.top5In'), incomingData: this.$t('monitor.inCallSum'), misscomingData: this.$t('monitor.top5InFail')}
            let types = Object.keys(headerConfig)
            // types.forEach(item => {
            //   let serie = { name: item.name, data: [], valueName: item.valueName }
            //   seriesArray.push(serie)
            // })
            datas.limitcomingData = datas.LimitcomingData
            datas.misscomingData = datas.MisscomingData
            datas.incomingComplete = datas.IncomingComplete
            datas.incomingData = datas.IncomingData
            datas.queue = datas.queueData
            for (let i = 0; i < types.length; i++) {
              let item = types[i]
              let currents = datas[item] || []
              let serie = { name: headerConfig[item], data: [], valueName: item }
              currents.forEach((one) => {
                let item = one.split(':')
                let time = parseInt(item[0])
                let num = parseInt(item[1])
                serie.data.push({x: time, y: num})
              })
              seriesArray.push(serie)
            }
            this.callInData.seriesArray = seriesArray
          } else {
            this.callInData.seriesArray.forEach((one) => {
              let item = datas[one.valueName][0].split(':')
              let time = parseInt(item[0])
              let num = parseInt(item[1])
              one.data.push({x: time, y: num})
            })
          }
        })
      },
      getCallInAreaData () {
        this.$store.dispatch('getCallInAreaData').then((res) => {
/*          {
            PROVINCE_CODE:"20",
              PROVINCE: "广东省",
            count: 3
          } */
          let data = res.data || []
          if (this.$refs.monitorArea) {
            this.$refs.monitorArea.renderMap(data)
          }
        })
      },
      getProvinceCodes () {
        this.$store.dispatch('getProvinceCodes').then((res) => {
          let data = res.data || []
          data = data.map((item) => {
            return {label: item.n, value: 'area_' + item._id}
          })
          this.$set(this.select, 'area', data)
        })
      },
      initChart (type) {
        // 只有在监控模块下才发请求
        if (this.$route.path.split('/')[2] === 'monitorNew') {
          this.getCallInAreaData()
        }
      }
    },
    mounted () {
    },
    activated () {
      if (this.$refs.monitorLine1) {
        this.$refs.monitorLine1.reflow()
      }
      if (this.$refs.monitorHeart) {
        this.$refs.monitorHeart.reflow()
      }
    },
    beforeMount () {
      this.init('phonePeersInit')
      this.init('phoneQueuesInit')
      this.initChart('init')
      this.getCallInDataIn6Hours('init')
      this.getProvinceCodes()
      if (this.agentType === 'manager' || this.agentType === 'admin') {
        let self = this
        window.setInterval(() => {
          self.initChart('update')
        }, 60000)
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl'
  .wrap
    padding 20px 10px 20px 10px
    box-sizing border-box
  .call-summary
    .main1
      margin-left: 175px
  .card
    width 150px
    margin-left: 3px
    padding 0 5px
    position absolute
    height: calc(100vh - 125px)
    .icon-peizhi
      position absolute
      right 10px
      font-size 16px
      top 10px
      color $c-main
      cursor pointer
    .card-item
      border-bottom 1px dashed $c-border2
      text-align center
      padding-bottom 8px
      &:last-child
        border 1px dashed #fff
      .num
        font-size 18px
        color $cf-gray1
        padding 5px 0 2px
        font-weight bold
      .num-word
        font-size 14px
        color $cf-gray4
      .tooltip
        margin-top -32px
  .main
    padding-top 0px
    padding-left 30px
    overflow-x hidden
    .border-line
      border-right 1px dashed $c-border1
      padding-right 30px
    .header
      padding-bottom 15px
    .title
      padding-bottom 16px
      font-size 14px
      color $cf-gray1
      .icon-peizhi
        padding-left 4px
        font-size 16px
        color $c-main
        cursor pointer
    .agent
      padding-bottom 16px
    .block
      padding-top 35px
  .square-wrap
    padding-top 10px
  .top-red
    color $c-pink
  .agent-cont
    border: 1px solid #e6e6e6;
    margin-right: 20px;
    margin-top: 10px;
    padding: 5px 15px;
    float: left;
    font-size 14px
    border-radius: 4px;
    .agent-sub
      color $cf-gray4
  .agent-title
    padding-right 10px
    color $c-main
  .padding-r
    padding-right 10px
    padding-top 20px
  .pie
    text-align center
    .pie-out
      display inline-block
      padding-right:10px
      margin-right: 10px
      border-right 1px solid $cf-gray4
  .icon-wenzishuoming
    color $c-main
    margin 0 5px
  .blod
    font-weight bold
  .tips
    padding-top 20px
    color $c-prompt
  .header-time
    font-size 13px
  .mulit-select
    width 200px
</style>
